import React from 'react';
import Redirect from 'umi/redirect';
import pathToRegexp from 'path-to-regexp';
import { connect } from 'dva';
import Authorized from '@/utils/Authorized';
import { getAuthority } from '@/utils/authority';
import Exception403 from '@/pages/exception-403';
//console.log(Authorized)

function AuthComponent({ children, location }) {

  //获得所有的的配置权限
  const routerData = children.props.route.routes;
  //console.log('children' + routerData);
  //判断用户是否登录，获取路由
  // if (login.authData === null || localStorage.getItem('antd')){
  //  // console.log(55555)
  //   const { routes, authority } = route;
  //   dispatch({
  //     type: 'menu/getMenuData',
  //     payload: { routes, authority, authData: localStorage.getItem('antd')}
  //   });
  // }

  let auth = getAuthority();
  //console.log('auth' + auth)
  //let isLogin = false;
  //if(auth !== null){
   const isLogin = auth && auth[0] !== 'guest' ;
  //}

 //console.log('isLogin'+isLogin)
  const getRouteAuthority = (path, routeData) => {
    //console.log('path'+path)
   //console.log('routeData'+JSON.stringify(routeData))
    let authorities;
    routeData.forEach(route => {
      // match prefix
     // console.log('prefix' + pathToRegexp(`${route.path}(.*)`))
     //console.log(pathToRegexp(`${route.path}(.*)`).test(path))
      if (pathToRegexp(`${route.path}(.*)`).test(path)) {//url的正则匹配
        authorities = route.key || authorities;
        //console.log(authorities)
        //console.log(typeof authorities)
        // 递归获得身份
        if (route.routes) {
         // console.log('进来'+JSON.stringify(route.routes))
          authorities = getRouteAuthority(path, route.routes) || authorities;
        }
      }
    });
    //console.log('结果' + authorities)
    // if (authorities == undefined){
    //   authorities = ['admin,user'];
    // }
    return authorities;
  };

  //console.log(getRouteAuthority(location.pathname, routerData));
  return (
    <Authorized
      authority={getRouteAuthority(location.pathname, routerData) === undefined ? "undefined≈" : getRouteAuthority(location.pathname, routerData)}
      noMatch={isLogin ? <Exception403 /> : <Redirect to="/user/login" />}
      //noMatch={isLogin ? '你没有权限' : <Redirect to="/user/login" />}
    >
      {children}
    </Authorized>
  );
}
export default connect()(AuthComponent);
